<template>
    <div class="divBox">
        <el-card class="p20">
            <div class="searchBox">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="销售单号" size="mini">
                        <el-input v-model="formInline.order_no" placeholder="销售单号" size="mini">
                            <el-button slot="append" icon="el-icon-search" @click="goSearchdialog"></el-button>
                        </el-input>
                    </el-form-item>
                    <el-form-item labe=" " size="mini">
                        <el-button type="primary" @click="onPrint" size="mini">打印</el-button>
                        <el-button type="success" @click="onYulang" size="mini">预览</el-button>
                    </el-form-item>
                    <el-form-item label=" " size="mini">
                        <el-select v-model="formInline.leixing" placeholder="请选择" size="mini">
                            <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                
            </div>
            <div class="p10">
                <div class="table-box" v-loading="loading">
                    <div class="table-container" >
                        <!-- <el-button type="primary" @click="exportToExcel">导出Excel</el-button>
                        <el-button type="primary" @click="exportToExcelImg">exportToExcelImg</el-button>
                        <input type="file" @change="handleImageUpload" accept="image/*">  -->
                        <div class="table-excel" v-if="xiaoshoudingdanRow">
                            <div>
                            <table >
                                <tbody>
                                    <tr>
                                        <td>生产单号</td>
                                        <td>{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'xiaoshoudanhao') }}</td>
                                        <td>客人下单日期</td>
                                        <td>
                                           {{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'created_at', 1) }}
                                        </td>
                                        <td>尺码</td>
                                        <td>{{ handlerFilterval(xiaoshoumixiData, 'kechima') }}</td>
                                        <td>生产线</td>
                                        <td>
                                            {{ handlerFilterval(xiaoshoumixiData, 'yszhongwenmiaoshu') }}
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>客人订单号</td>
                                        <td>{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'kepo') }}</td>
                                        <td>出货要求交期</td>
                                        <td>
                                            {{ handlerFilterval(xiaoshoumixiData, 'keqi', 1) }}
                                        </td>
                                        <td>倾角</td>
                                        <td></td>
                                        <td>客户代码</td>
                                        <td>{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'kehao') }}</td>
                                    </tr>
                                    <tr>
                                        <td>PLU号</td>
                                        <td>{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'PLU') }}</td>
                                        <td>订单数</td>
                                        <td>{{ handlerFilterval(xiaoshoumixiData, 'shuliang') }}</td>
                                        <td>圈弯</td>
                                        <td></td>
                                        <td>冲模编码</td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>客款号</td>
                                        <td>{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'kekuanhao') }}</td>
                                        <td>生产数</td>
                                        <td></td>
                                        <td>开放位</td>
                                        <td></td>
                                        <td></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>TS完成日期</td>
                                        <td></td>
                                        <td>TCS完成日期</td>
                                        <td></td>
                                        <td>订单类别</td>
                                        <td>{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'dingdanleibie') }}</td>
                                        <td></td>
                                        <td></td>
                                    </tr>
                                </tbody>
                            </table>

                            </div>
                            <!-- <div>
                                <table>
                                    <tbody>
                                        <tr>
                                            <td rowspan="7" colspan="1">图形{{ hadnlerFilterRowVal(xiaoshoudingdanRow, 'changkuanhao') }}</td>
                                            <td rowspan="7" colspan="5" >
                                                <div style="max-width:500px;position: relative;min-height:120px">
                                                    <div style="position: absolute;left:0;top:0;z-index:1;">
                                                        <img src="https://erp.langsenkeji.com/admin/imgs/GAI1529.png" style="width:500px;height:auto;"></img>
                                                    </div>
                                                </div>
                                            </td>
                                            <td rowspan="1" colspan="2">脾开料:154*23*4.0</td>
                                        </tr>
                                        <tr>
                                            <td rowspan="7" colspan="1"></td>
                                            <td rowspan="1" colspan="2"></td>
                                        </tr>
                                        <tr>
                                            <td rowspan="1" colspan="2"></td>
                                        </tr>
                                        <tr>
                                            <td rowspan="1" colspan="2"></td>
                                        </tr>
                                        <tr>
                                            <td rowspan="1" colspan="2"></td>
                                        </tr>
                                        <tr>
                                            <td rowspan="1" colspan="2"></td>
                                        </tr>
                                        <tr>
                                            <td rowspan="1" colspan="2"></td>
                                        </tr>
                                        
                                    </tbody>
                                </table>
                            </div> -->
                        </div>
                    </div>
                </div>
            </div>
        </el-card>
        <el-dialog :title="dialogtitle" :visible.sync="dialogVisible" width="60%" append-to-body>
            <selectDialog :total="diatotal" :tableInfo="selectInfo" :tableData="selectData" :searchField="searchField" :searchForm="searchForm" @handlerSearch="handlerSearch" @handlerSubmit="handlerSubmit"></selectDialog>
        </el-dialog>
    </div>
</template>

<script>
import {
    crudModuleListApi,
    crudModuleInfoApi,
    crudJoinListApi,
    databaseInfoApi,
    crudModuleUpdateApi,
    crudModuleFindApi,
    putUpdateFieldApi,
} from '@/api/develop'
import { getMrpAddProductApi } from '@/api/other'
import { getDictDatainfoApi, getDictDataListApi } from '@/api/form'
import draggable from 'vuedraggable';
import Sortable from 'sortablejs'
import oaFromBox from '@/components/common/oaFromBox'
import box from './components/box'
import wuliaoqingdan from './components/wuliaoqingdan.vue';
import addDrawernew from './components/addDrawernew'
import selectDialog from './components/selectDialog.vue';
// import { exportComplexTable } from '@/utils/exportExcel'
import { exportProductionOrder } from '@/utils/exportExcel';
import { exportProductionOrderImg } from '@/utils/exportExcelImage';
export default {
    name: 'boxList',
    components: {
      oaFromBox, box, draggable, wuliaoqingdan, addDrawernew, selectDialog
    },
    data() {
        return {
            formInline: {
                order_no: '',
                leixing:'',
            },
            options: [
               {label: '成品生产单', value: 1},
               {label: '配件生产单', value: 2}
            ],
            dialogVisible: false,
            dialogtitle:'选择销售单号',
            selectData: [],
            selectSearch: [],
            
            selectInfo: [],
            diatotal: 0,
            searchForm: [],
            searchField:[ 
                { field_name:'销售单号',field_name_en:'xiaoshoudanhao',form_value:'input',placeholder:'请输入代码或名称关键字'},
                { field_name:'客PO',field_name_en:'kepo',form_value:'input',placeholder:'请输入代码或名称关键字'},
                { field_name:'客款号',field_name_en:'kekuanhao',form_value:'input',placeholder:'请输入代码或名称关键字'},
                { field_name:'厂款号',field_name_en:'changkuanhao',form_value:'input',placeholder:'请输入代码或名称关键字'}
            ],
            publicSearch: { // 公共查询条件
                page: 1,
                limit: 30,
                is_system: 1,
                is_field_all:'',
                order_by: {},
                scope_frame: 'all',
                show_search_type: '0',
                view_search: [],
                view_search_boolean: '',
            },
            searchObj: {},
            xiaoshoudingdanRow: null,

            xiaoshoumixiData: [],

            // 主表数据
      mainTableData: {
        productionNo: 'AF231549',
        orderDate: '2023-07-21',
        size: '531719-140',
        productionLine: '注塑线',
        customerOrderNo: '4500140913',
        deliveryDate: '2023-11-20',
        lowEnd: '11度',
        customerCode: '019',
        pluNo: '',
        orderQuantity: '40',
        customerSet: '400C',
        moldNo: '精制开料',
        styleNo: 'STW027',
        productionQuantity: '46',
        openPosition: '132.1MM',
        tsCompletionDate: '-',
        tcsCompletionDate: '-',
        orderType: '重量',
        example1: '150*26.1*4.0',
        example2: '158*60.3*6.0',
        cuttingExample: '34*13*6.0'
      },
      // 物料清单数据
      materialList: [
        {
          category: '胶物料',
          materialCode: 'BL-2Y2303-43-JY01',
          materialDescription: '胶物料 2Y2303 实卡其他 1400*170*4.3（全余） YHDQ0105内侧加剂30分钟脱机PU的卷，颜色按标准色为YHDQ0105收货 For De Rigo order',
          quantity: '0.5',
          unit: '条',
          remark: '原料52付/条开料32付'
        },
        {
          category: '内含',
          materialCode: 'HZ0033',
          materialDescription: 'HZ0033 019客内含 6付/盒 尺寸 21.7*17.2*7CM（2025-01-13更新版本R035-ACC-B001AG增加符号）新旧可混用（同名供样方）',
          quantity: '2',
          unit: '个',
          remark: ''
        },
        // 其他物料数据...
      ],
            loading: true,
            total: 0,
            wlqdtabelShownew: false,
           
            search: [], // 当前列表顶部的搜索查询参数数组
            draggingRow: null,
            dragOptions: {
                animation: 150,
                handle: '.drag-handle',
                ghostClass: 'ghost'
            },
            boxid:0,
            pagestatus: 2,
            keyName: '',
            searchForm: {}, // 最后当前查询条件
            allSearchForm: {
                page: 1,
                limit: 15,
                table: '',
                data: ''
            },
            showFieldData: [],
            zidiangData: null,
            dictForm: { // 字典数据
                types: '',
                level: 1,
                pid:''
            },
            selectTableRow: [],
            baseindex: 0,
            zidianbaseData:{
                peijianleixing:[],
                gongxushezi:[]
            },
            headertitle:'物料清单',
            startshowfields: [],
            addDrawerShownew: false,

            productionData: {
        productionNo: 'AF231549',
        orderDate: '2023-07-21',
        size: '53E119-140',
        productionLine: '注数线',
        customerOrderNo: '4500140913',
        deliveryDate: '2023-11-20',
        lowAngle: '11度',
        customerCode: '019',
        pluNo: 'STW027',
        orderQuantity: '40',
        measure: '400C',
        moldNo: '精制开料',
        customerTitle: '',
        productionQuantity: '46',
        openPosition: '132.1MM',
        tsCompletionDate: '-',
        tcsCompletionDate: '-',
        orderType: '翻单',
        exampleHorizontal: '2023-06-01',
        exampleVertical: '2023-06-02',
        materialList: [
          {
            category: '胶物料',
            materialCode: 'BL-2Y2303-43-JY01',
            materialDescription: '胶物料 2Y2303 实卡套色 1400*170*4.3（全装） YHDO0105机前端30分钟的专用设备，颜色按需定制/ID00105收货 For De Rigo order',
            quantity: '0.5',
            unit: '条',
            remark: '原料52付/条,开料23付'
          },
          {
          category: '胶物料2',
          materialCode: 'BL-2Y2303-43-JY01',
          materialDescription: '胶物料 2Y2303 实卡其他 1400*170*4.3（全余） YHDQ0105内侧加剂30分钟脱机PU的卷，颜色按标准色为YHDQ0105收货 For De Rigo order',
          quantity: '0.5',
          unit: '条',
          remark: '原料52付/条开料32付'
        },
        {
          category: '内含',
          materialCode: 'HZ0033',
          materialDescription: 'HZ0033 019客内含 6付/盒 尺寸 21.7*17.2*7CM（2025-01-13更新版本R035-ACC-B001AG增加符号）新旧可混用（同名供样方）',
          quantity: '2',
          unit: '个',
          remark: ''
        },
          // 其他物料数据...
        ],
        imageBase64: null // 存储图片的Base64数据
      }
        }
    },

  
    created() {
        
        
    },
    mounted() {
        const routeString = this.$route.path
        const routeArray = routeString.split('/').filter((item) => item !== '')
        this.keyName = routeArray[3]
        this.loading = false; 

        
    },
    methods: {
        async exportToExcel() {
            try {
                await exportProductionOrder(this.productionData, '生产订单.xlsx');
                this.$message.success('导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败');
            }
        },
        async exportToExcelImg() {
            try {
                await exportProductionOrderImg(this.productionData, '生产订单.xlsx');
                this.$message.success('导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败: ' + error.message);
            }
        },
        handleImageUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = (e) => {
                this.productionData.imageBase64 = e.target.result.split(',')[1];
            };
            reader.onerror = () => {
                this.$message.error('图片上传失败');
            };
            reader.readAsDataURL(file);
        },
        // 辅助方法：将图片URL转换为Base64
        async urlToBase64(imageUrl) {
            const response = await fetch(imageUrl);
            const blob = await response.blob();
            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onload = () => {
                resolve(reader.result.split(',')[1]);
                };
                reader.readAsDataURL(blob);
            });
        },
        handleEdit(index, row) {
           console.log(index, row);
        },
        // 打印
        onPrint(){

        },
        //预览
        onYulang(){

        },

        goSearchdialog(){ 
           this.selectInfo = [
              { field_name_en: 'xiaoshoudanhao', field_name: '销售单号', form_value:'input'},
              { field_name_en: 'kehao', field_name: '客号', form_value:'input'},
              { field_name_en: 'kepo', field_name: '客PO', form_value:'input'},
              { field_name_en: 'kekuanhao', field_name: '客款号', form_value:'input'},
              { field_name_en: 'changkuanhao', field_name: '厂款号', form_value:'input'},
           ]
           if(this.formInline.order_no){
              this.searchObj = JSON.parse(JSON.stringify(this.publicSearch));
              this.searchObj.xiaoshoudanhao = this.formInline.order_no;
              this.searchForm.xiaoshoudanhao = this.formInline.order_no;
              this.handlerDialogTable(this.searchObj);
           }
           this.dialogVisible = true;
        },
        // 搜索
        handlerSearch(data){
            console.log("daings", data)
            this.searchObj = Object.assign({}, this.publicSearch, data)
            this.handlerDialogTable(this.searchObj);

        },
        // 确定
        handlerSubmit(index, row){
            console.log(index, row)
            
            this.xiaoshoudingdanRow = row || null;
            this.formInline.order_no = row.xiaoshoudanhao
            console.log("xiaoshoudingdanRow", this.xiaoshoudingdanRow)
            if(row.id){
                // let searchdata = this.publicSearch;
                // searchdata.xiaoshoudingdanid = row.id;
                // this.getList(searchdata);
                this.handlerJoinList(row.id);
            }
            this.dialogVisible = false;
            
        },
        handlerDialogTable(formdata){
            crudModuleListApi('xiaoshoudingdan',formdata).then((res)=>{
                this.selectData = res.data.list;
                this.diatotal = res.data.count;
            }).catch((err)=>{

            })
        },
        
        
        // 获取物料清单列表
        async getList(formData) {
            crudModuleListApi('xiaoshoumingxi', formData).then((res)=>{
                this.xiaoshoumixiData = res.data.list;
                
            }).catch((err)=>{

            })
        },
        handlerJoinList(id){
            let formdatas = {
                joins: [
                    {
                        type: "leftJoin",
                        table: "yushepaiqi",
                        alias: "y",
                        on: [
                            [
                                "m.shengchanxian",
                                "y.id"
                            ]
                        ]
                    },
                    {
                        type: "leftJoin",
                        table: "wuliaoxinxi",
                        alias: "x",
                        on: [
                            [
                                "m.wuliaobianma",
                                "x.id"
                            ]
                        ]
                    }
                ],
                conditions: {
                     'm.xiaoshoudingdanid': id,  
                     
                },
                fields: [
                    "m.*",
                    "x.item_sn as item_sn",
                    "y.zhongwenmiaoshu as yszhongwenmiaoshu",
                    "x.bomm_ap_flag as bomm_ap_flag",
                    "x.design_sn as design_sn"

                ],
                order: {
                    "m.id": "desc"
                }
            }


            this.allSearchForm.table = 'xiaoshoumingxi as m'
            this.allSearchForm.data = encodeURI(JSON.stringify(formdatas))
            console.log("|dings11")
            this.getListall(this.allSearchForm)
        },
        async getListall(formdata){
            crudJoinListApi(formdata).then((res)=>{
                this.xiaoshoumixiData = res.data.list;
            }).catch((err)=>{

            })
        },
        // 数组中数据处理
        handlerFilterval(data, name, index=0){
            if(data && data.length > 0){
                if(index == 1){ // 日期格式
                    if(data[0][name]){
                       return data[0][name].slice(0, 10);
                    }else{
                       return '-'
                    }
                }else{
                    return data[0][name] ? data[0][name]: '-'
                }
            }else{
               return ''
            }
        },
        hadnlerFilterRowVal(data, name, index=0){
            if(data){
                if(index == 1){ // 日期格式
                    if(data[name]){
                       return data[name].slice(0, 10);
                    }else{
                       return '-'
                    }
                }else{
                    return data[name] ? data[name]: '-'
                }
            }else{
               return ''
            }
        },
        
        // 实体表对数据进行处理返回name
        handleraccociation(val, fieldname){
            if(val){
                let didList = this.zidiangData[fieldname];
                if(didList && didList.length>0 ){
                    for(let i=0;i< didList.length;i++){
                        if(fieldname == 'kehao'){
                            if(val == didList[i].kehao){
                               return didList[i].id;
                            } 
                        }else{
                          if(val == didList[i].leibiedaima){
                            return didList[i].zhongwenmiaoshu;
                          }  
                    }   }
                }
                return val;
            }else{
                return ''
            }
        },
        handlerValue(val){
            if(val){
                if(Array.isArray(val)){
                    return val.join(',')
                }else if(this.isObject(val)){
                    return val.name || '';
                }else{
                    return val;
                }
            }else{
                return ''
            }
        },
        // 判断是否是object对象
        isObject(value) {
            return value !== null && Object.prototype.toString.call(value) === '[object Object]';
        },
        // 显示tablecolumn宽度
        handelrWidth(item){
            let textname = ['gongsidaima', 'item_sn', 'wuliaozhongwenmiaoshu', 'item_depc'];
            let textname2 = ['kehaomingcheng', 'shuliang', 'mianfeishu', 'choudanshu', 'shengchanshu']
            let textname3 = ['danwei', 'laiyuan','zhuangtai', 'choudanbeizhu']
            let texttime = ['updated_at', 'created_at']
            if(textname.includes(item.field_name_en)){
                return '220px';
            }else if(textname2.includes(item.field_name_en)){
                return '60px'
            }else if(textname3.includes(item.field_name_en)){
                return '90px'
            }else if(texttime.includes(item.field_name_en)){
                return '150px'
            }else{
                return '120px'
            }
        },
        handlerDisabel(filedname){
            let textdata = ['gongsidaima', 'danwei', 'danjuleixing']
            if(textdata.includes(filedname)){
                return true;
            }
            return false;
        },
        handlerDisabelval(val, fieldname){
            let name = '';
            if(val){
                let didList = this.zidiangData[fieldname];
                if(didList && didList.length>0 ){
                    for(let i=0;i< didList.length;i++){
                        if(val == didList[i].name || val == didList[i].value){
                            return didList[i].name;
                        }
                    }
                }
                return val;
            }
            return name;
        }



    }
}
</script>

<style lang="scss" scoped>

/deep/ .draggable-table .el-textarea__inner{
  border:none!important;
}
/deep/ .draggable-table .el-input__inner{
  border:none!important;
  padding: 0 2px!important;
}
/* select 上拉箭头 */
/deep/ .draggable-table .el-icon-arrow-up:before{
   content:''
}
/deep/ .draggable-table .el-input--medium .el-input__icon.el-icon-circle-close{
   line-height:28px!important;
}
/deep/ .draggable-table .el-input--suffix .el-input__inner{
   padding: 0 2px!important;
}
/deep/ .draggable-table .el-input__icon{
    width:16px;
}
/deep/ .draggable-table .el-input--medium .el-input__icon{
    line-height:28px;
}
/deep/ .el-table .cell{
  line-height: 20px;
}

.drag-handle {
  cursor: move;
}

.drag-wrapper {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.drag-wrapper > * {
  pointer-events: all;
}

.drag-item {
  height: 48px; /* 与行高一致 */
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

.flip-list-move {
  transition: transform 0.5s;
}
.divBox {
    height: 100%;
}

.mt16 {
    margin-top: 7px;
}

.img {
    display: block;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-right: 4px;
}

.prompt-bag {
    background-color: #edf5ff;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #606266;
}

/deep/.el-button--small {
    font-size: 13px;
}

.el-icon-question {
    cursor: pointer;
    color: #1890ff;
    font-size: 15px;
}

/deep/ .el-card__body {
    padding: 0 20px;
}

.iconzhuyaobumen {
    color: #ff9900;
}

.boder-left {
    min-height: calc(100vh - 77px);
    border-left: 1px solid #eeeeee;
}

.p20 {
    padding: 20px 0;
}

.table-container {
    margin-top: 10px;
}
/* 如果需要拖拽手柄 */
.drag-handle {
  cursor: move;
}
.table-excel{
    border:1px solid #333;
    width:800px;
}
.table-excel tr{
    border-bottom:1px solid #e0e0e0;vertical-align: middle;
}
.table-excel td{
    border-left: 1px solid #e0e0e0;
    width:100px;color:#333;font-size:12px;
    text-align: center;padding:5px 0;line-height: 18px;
   vertical-align: middle;
}

</style>